import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:food_hub_app/widgets/common/form.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'dart:io';

class RecordFormPage extends StatefulWidget {
  const RecordFormPage({super.key});

  @override
  State<RecordFormPage> createState() => _RecordFormPageState();
}

class _RecordFormPageState extends State<RecordFormPage> {
  final _formKey = GlobalKey<FormBuilderState>();
  final _focusNode = FocusNode();
  static const String _nameField = 'name';
  static const String _dateField = 'date';

  final ImagePicker _picker = ImagePicker();
  File? imageUrl; // 改为单张图片变量

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('新增记录', style: TextStyle(color: Colors.white)),
        backgroundColor: theme.primaryColor,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      backgroundColor: const Color(0xFFF5F5F5),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(5),
          child: Card(
            elevation: 0,
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Padding(
              padding: const EdgeInsets.all(10),
              child: _buildFormBuilder(),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildFormBuilder() {
    return FormBuilder(
      key: _formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          buildFormLabel('菜谱名称', required: true),
          const SizedBox(height: 8),
          _buildNameTextField(),
          const SizedBox(height: 10),

          buildFormLabel('完成时间', required: true),
          const SizedBox(height: 8),
          _buildDateTextField(),
          const SizedBox(height: 10),

          buildFormLabel('上传图片', required: true),
          const SizedBox(height: 10),
          _buildImageUploadArea(),

          const SizedBox(height: 10),
          buildFormButtonGroup(context: context, onConfirm: () => _submitForm),
        ],
      ),
    );
  }

  /// 菜谱名称输入框
  Widget _buildNameTextField() {
    return FormBuilderTextField(
      name: _nameField,
      focusNode: _focusNode,
      decoration: buildInputDecoration(context: context, hintText: '请输入菜谱名称'),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入菜谱名称';
        }
        return null;
      },
    );
  }

  /// 完成时间选择框
  Widget _buildDateTextField() {
    return FormBuilderTextField(
      name: _dateField,
      readOnly: true,
      decoration: buildInputDecoration(
        context: context,
        hintText: '请选择完成时间',
        prefixIcon: const Icon(
          Icons.calendar_month,
          size: 20,
          color: Color(0xFF86909C),
        ),
      ),
      onTap: () => _onSelectDate(),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请选择完成时间';
        }
        return null;
      },
    );
  }

  /// 图片上传区域（预览+上传按钮）
  Widget _buildImageUploadArea() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (imageUrl != null)
          _buildImagePreviewItem()
        else
          _buildImageUploadButton(),
      ],
    );
  }

  Widget _buildImagePreviewItem() {
    return Container(
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Stack(
          children: [
            GestureDetector(
              onTap: () => _showImagePreview(),
              child: Image(
                image: FileImage(imageUrl!),
                width: 120,
                height: 120,
                fit: BoxFit.cover,
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Container(
                    width: 120,
                    height: 120,
                    color: Colors.grey[100],
                    child: const Center(
                      child: CircularProgressIndicator(strokeWidth: 2),
                    ),
                  );
                },
              ),
            ),

            Positioned(
              top: 6,
              right: 6,
              child: GestureDetector(
                onTap: _removeImage,
                child: Container(
                  width: 24,
                  height: 24,
                  decoration: const BoxDecoration(
                    color: Colors.red,
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black26,
                        blurRadius: 2,
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: const Icon(Icons.close, color: Colors.white, size: 16),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showImagePreview() {
    showDialog(
      context: context,
      barrierColor: Colors.black87, // 半透明黑色背景
      builder:
          (context) => Dialog(
            backgroundColor: Colors.transparent,
            elevation: 0,
            insetPadding: const EdgeInsets.all(16),
            child: GestureDetector(
              onTap: () => Navigator.pop(context), // 点击空白处关闭
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  // 预览图添加轻微阴影
                  boxShadow: [BoxShadow(color: Colors.black38, blurRadius: 10)],
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Image.file(
                    imageUrl!,
                    fit: BoxFit.contain, // 保持图片比例
                    height: MediaQuery.of(context).size.height * 0.7, // 限制最大高度
                  ),
                ),
              ),
            ),
          ),
    );
  }

  /// 图片上传按钮
  Widget _buildImageUploadButton() {
    return InkWell(
      onTap: _pickImage,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        width: 96,
        height: 96,
        decoration: BoxDecoration(
          color: const Color(0xFFF2F3F5),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: const Color(0xFFDCDFE6), width: 1),
        ),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.add, color: Color(0xFF86909C), size: 24),
            SizedBox(height: 6),
            Text(
              '添加图片',
              style: TextStyle(color: Color(0xFF86909C), fontSize: 13),
            ),
          ],
        ),
      ),
    );
  }

  /// 选择日期
  Future<void> _onSelectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      builder:
          (context, child) => Theme(
            data: ThemeData.light().copyWith(
              primaryColor: Theme.of(context).primaryColor,
              colorScheme: ColorScheme.light(
                primary: Theme.of(context).primaryColor,
              ),
              buttonTheme: const ButtonThemeData(
                textTheme: ButtonTextTheme.primary,
              ),
            ),
            child: child!,
          ),
    );

    if (picked != null) {
      _formKey.currentState?.fields[_dateField]?.didChange(
        DateFormat('yyyy-MM-dd').format(picked),
      );
    }
  }

  /// 选择图片（限制单张）
  Future<void> _pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        imageUrl = File(image.path); // 直接覆盖现有图片
      });
    }
  }

  /// 移除图片
  void _removeImage() {
    setState(() {
      imageUrl = null;
    });
  }

  /// 提交表单
  void _submitForm() {
    if (_formKey.currentState?.saveAndValidate() ?? false) {
      if (imageUrl == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('请上传图片'),
            backgroundColor: Colors.red,
            behavior: SnackBarBehavior.floating,
          ),
        );
        return;
      }

      final formData = {
        ..._formKey.currentState!.value,
        'imageUrl': imageUrl?.path, // 单张图片路径
      };

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('提交成功！'),
          behavior: SnackBarBehavior.floating,
        ),
      );
      print('表单数据: $formData');
    }
  }
}
